<template>
  <div class="page-wrap">
    <el-tabs v-model="tabType" type="card">
      <el-tab-pane label="图表" name="图表"></el-tab-pane>
      <el-tab-pane label="明细" name="明细"></el-tab-pane>
    </el-tabs>
    <div class="top-wrap">
      车间 <Gap />
      <el-select :popper-append-to-body="false" v-model="currentWorkshop" placeholder="请选择车间">
        <el-option v-for="item in workshops" :key="item.id" :label="item.wname" :value="item.id" />
      </el-select>
      <Gap /> 机台 <Gap />
      <el-select :popper-append-to-body="false" v-model="currentMid" placeholder="请选择机台" style="width: 220px">
        <el-option v-for="item in macLis" :key="item.id" :label="item.mname + '(' + item.mid + ')'" :value="item.mid" />
      </el-select>
      <Gap />
      <el-button @click="handleSearchBtnClick" slot="append" icon="el-icon-search"> 检索</el-button>
    </div>
    <div class="spin-status">
      <div class="spin-status-inner" v-show="tabType === '明细'">
        <el-table size="mini" border :data="leftData" height="calc(100% - 30px)">
          <!-- <el-table-column prop="PAGE_ROW_NUMBER" label="左" width="50" align="center" /> -->
          <!-- <el-table-column prop="mid" label="机台编号" width="150" /> -->
          <el-table-column prop="cn_status" label="状态" min-width="50" align="center">
            <template slot-scope="scope"> {{ scope.row.cn_status }} </template>
          </el-table-column>
          <el-table-column prop="startTime" label="开始时间" min-width="150" align="center">
            <template slot-scope="scope"> {{ scope.row.startTime }}</template>
          </el-table-column>

          <el-table-column prop="endTime" label="结束时间" min-width="150" align="center">
            <template slot-scope="scope"> {{ scope.row.endTime }}</template>
          </el-table-column>
          <el-table-column prop="jgsj" label="间隔时间" min-width="106" align="center">
            <template slot-scope="scope"> {{ scope.row | toDotTime }} </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange($event, 'Left')"
          @current-change="handleCurrentChange($event, 'Left')"
          :current-page="leftPageInfo.pageNum"
          :page-sizes="[100, 500]"
          :page-size="leftPageInfo.pageSize"
          layout="total,  prev, pager, next,sizes"
          :total="leftPageInfo.total"
        />
      </div>
      <div ref="ct" class="chart-wrap" v-show="tabType === '图表'"></div>
    </div>
  </div>
</template>
<script>
import BlockTitle from '@/components/BlockTitle/index.vue'
import request from '@/utils/request'
import dayjs from 'dayjs'
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme

function minuteToCh(t) {
  let timeStr = ''
  let converted = Math.floor(t / (24 * 60))
  if (converted > 0) timeStr += `${converted}天`
  t = t % (24 * 60)
  converted = Math.floor(t / 60)
  if (converted > 0) timeStr += `${converted}小时`
  t = t % 60
  if (t > 0) timeStr += `${t}分钟`
  return timeStr
}
const animationDuration = 6000
var spinlist = [{ label: '全部', value: '全部' }]
for (let i = 1; i < 100; i++) {
  spinlist.push({ label: i, value: i })
}
//console.log(BlockTitle)
export default {
  name: 'MachineInfoRun',
  components: {
    BlockTitle,
    Gap: {
      template: `<div style="width:10px"></div>`,
    },
    GapX: {
      template: `<div style="width:20px"></div>`,
    },
  },
  filters: {
    toTime(t) {
      return t ? dayjs(t).format('MM-DD HH:mm:ss') : '-'
    },

    twoNum(e) {
      return (e < 10 ? '0' : '') + e
    },
    thrNum(e) {
      return ('000' + e).slice(-3)
    },
    toDotTime(r) {
      const now = r.endTime ? dayjs(r.endTime) : dayjs()
      let t = now.diff(r.startTime, 'second')
      let timeStr = ''
      let converted = Math.floor(t / (24 * 60 * 60))
      if (converted > 0) timeStr += `${converted}天`
      t = t % (24 * 60 * 60)
      converted = Math.floor(t / (60 * 60))
      if (converted > 0) timeStr += `${converted}时`
      t = t % (60 * 60)
      converted = Math.floor(t / 60)
      if (converted > 0) timeStr += `${converted}分`
      converted = t % 60

      if (converted > 0) timeStr += `${converted}秒`
      return timeStr
    },
  },
  data() {
    return {
      tabType: '图表',
      except: '全部',
      timeRange: [],
      colorMap: {
        落纱: '#FFA939',
        纺纱: '#00DBAA',
        停机: '#7F9AAF',
        离线: '#FF6155',
      },
      spinNum: '全部',
      spinlist,
      mid: '1234567890ABCDEF',
      sqlList: [
        {
          value: `select * from spin_exceptional where mid='000000000000000001' and inx = 0 order by side,inx,type,startTime `,
          label: 'all',
        },
      ],
      exceptChr: [
        { label: '0-断头', value: 0 },
        { label: '1-掉线', value: 1 },
        { label: '2-闲置', value: 2 },
        { label: '3-弱捻', value: 3 },
        { label: '4-严重弱捻', value: 4 },
        { label: '5-锭子故障', value: 5 },
        { label: '全部', value: '全部' },
      ],
      // exceptChr: ['0-断头', '1-掉线', '2-闲置', '3-弱捻', '4-严重弱捻', '5-锭子故障'],
      leftPageInfo: { pageSize: 100, pageNum: 1 },
      rightPageInfo: { pageSize: 100, pageNum: 1 },
      customColWidth: {
        id: 150,
        PackType: 80,
        Side: 60,
        SpinStartAddr: 70,
        SpinNumber: 60,
      },

      workshops: [],
      currentWorkshop: '',

      macLis: [],
      currentMid: '',

      dataList: [],
      propList: [],
      leftData: [],
      rightData: [],
      currentRow: '',
      pageInfo: [],
    }
  },
  computed: {},
  created() {
    this.getData()
    // const defaultSqlList = localStorage.getItem('sqlList_except')
    // if (defaultSqlList) this.sqlList = JSON.parse(defaultSqlList)
    // const defaultSql = localStorage.getItem('defaultSql_except')
    // if (defaultSql) this.sql = this.defaultSql = defaultSql
  },
  mounted() {
    // window.dj = dayjs
    //console.log(dayjs)
    // this.$nextTick(() => {
    //   this.initChart()
    // })
    this.init()
  },
  methods: {
    async init() {
      try {
        this.$ShowLoading()
        let r = await request({
          url: '/db/getData',
          method: 'post',
          data: { sql: `select * from workshop_info order by wid`, pagenum: 1, pagesize: 100 },
        })
        this.workshops = r.obj.list
        this.currentWorkshop = this.workshops[0].id

        r = await request({
          url: '/db/getData',
          method: 'post',
          data: { sql: `select * from mac_info where workShop = '${this.currentWorkshop}' order by mid`, pagenum: 1, pagesize: 100 },
        })
        this.macLis = r.obj.list
        this.currentMid = this.macLis[0].mid
      } catch (e) {
        console.log(e)
      }
    },

    initChart(series, startTime) {
      this.chart = echarts.init(this.$refs.ct, 'macarons')

      this.chart.setOption({
        min: 0, // 开始于0小时
        max: 1440, // 结束于24小时（注意：这假设您的数据是小时数）

        tooltip: {
          trigger: 'item',
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        legend: {
          data: ['落纱', '纺纱', '停机', '离线'],
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        dataZoom: [
          {
            type: 'slider',
            xAxisIndex: 0,
            endValue: 1440,
            filterMode: 'none',
          },
        ],
        xAxis: {
          type: 'value',
          maxInterval: 24,
          interval: 60,
          axisLabel: {
            max: 1440,
            formatter: function (value) {
              let hours = Math.ceil(value / 60)
              // let minutes = value % 60
              // minutes = minutes < 10 ? '0' + minutes : minutes
              return hours + ':00'
            },
          },
        },
        yAxis: {
          type: 'category',
          data: [
            '机台1',
            '机台2',
            '机台3',
            '机台4',
            '机台5',
            '机台6',
            '机台7',
            '机台8',
            '机台9',
            '机台10',
            '机台11',
            '机台12',
            '机台13',
            '机台14',
            '机台15',
            '机台16',
            '机台17',
            '机台18',
            '机台19',
            '机台20',
            '机台21',
            '机台22',
            '机台23',
          ],
        },
        series,
        // series: [
        //   {
        //     name: '纺纱',
        //     type: 'bar',
        //     barMaxWidth: 32,
        //     //barMinHeight: 1,
        //     stack: '总量',
        //     label: {
        //       normal: {
        //         show: true,
        //         position: 'insideRight',
        //       },
        //     },
        //     tooltip: {
        //       formatter: (p, x, d) => {
        //         console.warn(p, x, d)
        //         console.warn(p.value)

        //         return `<div style="#FFF;width:100px;font-size:12px">
        //           <p style="color:#333">${p.name}</p>
        //           <p style="color:#666">${p.value}</p>
        //           <p style="color:#666">${p.value}</p>
        //         </div>`
        //       },
        //       backgroundColor: '#FFF',
        //     },

        //     data: [180, 440],
        //   },
        //   {
        //     name: '落纱',
        //     type: 'bar',
        //     stack: '总量',
        //     label: {
        //       normal: {
        //         show: true,
        //         position: 'insideRight',
        //       },
        //     },
        //     data: [180, 1000],
        //   },
        // ],
      })
    },
    handleSearchBtnClick() {
      this.getData()
    },
    handleSizeChange(e, side) {
      console.log('handleSizeChange', e)
      if (side == 'Left') {
        this.leftPageInfo.pageSize = e
      } else {
        this.rightPageInfo.pageSize = e
      }
      this.getData(side)
    },
    handleCurrentChange(e, side) {
      if (side == 'Left') {
        this.leftPageInfo.pageNum = e
      } else {
        this.rightPageInfo.pageNum = e
      }
      this.getData(side)
    },
    async getData(side) {
      console.log(111)

      let sql = `SELECT * FROM [lce].[dbo].[v_mac_status] order by newsj desc`
      const { mid, except, currentRow, spinNum } = this
      console.log(this.currentRow, this.spinNum)
      this.$ShowLoading()
      // const loading = this.$loading({
      //   lock: true,
      //   text: `正在加载数据`,
      //   spinner: 'el-icon-loading',
      //   background: 'rgba(0, 0, 0, 0.7)',
      // })
      let pageInfo = this.leftPageInfo
      try {
        const { pageNum: pagenum, pageSize: pagesize } = pageInfo
        const res = await request({
          url: '/db/getData',
          method: 'post',
          // data: {
          //   spName: 'sp_dtbb',
          //   params: [
          //     { isnum: false, value: '2024-03-01' },
          //     { isnum: true, value: 123 },
          //   ],
          //   pagenum: 1,
          //   pagesize: 20,
          // },
          data: { sql, pagenum, pagesize },
        })
        if (res.obj.list.length == 0) {
          // loading.close()
          return
        }

        this.leftPageInfo = { ...res.obj }
        // if (side == 'Left') {
        this.leftData = res.obj.list
      } catch (e) {
        console.log('Error:', e)
      } finally {
        this.$CloseLoading()
      }
      sql = `SELECT * FROM [lce].[dbo].[v_mac_status] where newsj > convert(varchar(10),getdate(),120) order by newsj asc`
      // sql = `SELECT * FROM [lce].[dbo].[v_mac_status] where newsj > '2024-08-19' order by newsj asc`
      this.$ShowLoading()
      try {
        const res = await request({
          url: '/db/getData',
          method: 'post',
          data: { sql, pagenum: 1, pagesize: 10000 },
        })
        const _start = res.obj.list[0].startTime
        res.obj.list.unshift({ ...res.obj.list[0], startTime: dayjs().format('YYYY-MM-DD'), endTime: _start, cn_status: '离线' })
        const series = res.obj.list.map((e) => {
          const end = e.endTime ? dayjs(e.endTime) : dayjs()
          let t = end.diff(e.startTime, 'minute')

          return {
            name: e.cn_status,
            type: 'bar',
            barMaxWidth: 32,
            //barMinHeight: 1,
            stack: '总量',
            // label: {
            //   normal: {
            //     show: true,
            //     position: 'insideRight',
            //   },
            // },
            itemStyle: {
              normal: {
                color: this.colorMap[e.cn_status],
              },
            },
            tooltip: {
              formatter: (p, x, d) => {
                console.warn(p)
                return `<div style="font-size:12px;color:#666">
                  <span style="margin-right:4px;font-weight:bold;">${p.seriesName}:</span>
                  <span style="">${minuteToCh(p.value)}</span>
                </div>`
              },
              backgroundColor: '#FFF',
            },
            data: [t],
          }
        })
        this.initChart(series)

        console.warn(res)
      } catch (e) {
        console.log('getdata request2 err:', e)
      } finally {
        this.$CloseLoading()
      }
    },
  },
}
</script>
<style lang="scss" scoped>
@import '~@/styles/variables.scss';

.page-wrap {
  padding: 10px 20px;
  box-sizing: border-box;
}

.sub-item {
  width: 44px;
  text-align: center;
  border-right: 1px #eee solid;
  flex-shrink: 0;
}

.top-wrap {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.spin-status {
  margin-top: 10px;
  height: calc(100vh - 170px);
  display: flex;
}

.spin-status-inner {
  width: 100%;
}
.chart-wrap {
  width: 100%;
  height: calc(100vh - 170px);
  background: #eee;
}
</style>
